from flask import Flask, request,  render_template, redirect, url_for,send_from_directory, make_response
import os
from datetime import datetime, timedelta
import hashlib
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif','webp'}
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024  # 限制2MB


def generate_hash_filename(file):
    file_hash = hashlib.md5(file.read()).hexdigest()
    file.seek(0)  # 重置文件指针
    return f"{file_hash}.jpg"


@app.route('/')
def index():
    files = os.listdir(app.config['UPLOAD_FOLDER'])
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return 'No file uploaded', 400
    file = request.files['file']
    if file.filename == '':
        return 'Empty filename', 400
    filename = generate_hash_filename(file)
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return f"""Upload successful: {filename}
    <a href="/uploads/{filename}">点击跳转</a><br>
    md: ![书念图床]({filename})

    """

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    response = make_response(send_from_directory(app.config['UPLOAD_FOLDER'], filename))
    response.headers['Cache-Control'] = 'public, max-age=1209600'  # 缓存2周
    response.headers['Expires'] = (datetime.now() + timedelta(seconds=1209600)).strftime('%a, %d %b %Y %H:%M:%S GMT')
    return response

@app.route('/delete', methods=['GET','POST'])
def delete_file():
    password = request.form.get('password')
    filename = request.form.get('filename')
    if request.method == 'POST':
        if password != "114514":
            return "Invalid password", 403

        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        print(file_path)
        if not os.path.exists(file_path):
            return "File not found", 404
        try:
            os.remove(file_path)
            return "OK"
        except Exception as e:
            return f"Delete failed: {str(e)}", 500

    return render_template('delete.html')

if __name__ == '__main__':
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    app.run(debug=True)

